use log4rs::append::console::ConsoleAppender;
use log4rs::append::rolling_file::{
    policy::compound::{
        roll::fixed_window::FixedWindowRoller, trigger::size::SizeTrigger, CompoundPolicy,
    },
    RollingFileAppender,
};
use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;

pub fn config_log(app_name: &str) {
    // Create console appender
    let stdout = ConsoleAppender::builder()
        .encoder(Box::new(PatternEncoder::new("{d} [{l}] {M}:{L} - {m}{n}")))
        .build();

    // Create size trigger: roll when file > 20 bytes
    let trigger = SizeTrigger::new(2 * 1024 * 1024); // 2MB in bytes

    // Create fixed window roller: keep 7 files, name pattern logs/bwexam-1.log .. bwexam-7.log
    let roller = FixedWindowRoller::builder()
        .build(format!("logs/{}-{{}}.log", app_name).as_str(), 7)
        .expect("Failed to build roller");

    // Combine trigger and roller into compound policy
    let policy = CompoundPolicy::new(Box::new(trigger), Box::new(roller));

    // Create rolling file appender
    let rolling_file = RollingFileAppender::builder()
        .encoder(Box::new(PatternEncoder::new("{d} [{l}] {M}:{L} - {m}{n}")))
        .build(format!("logs/{}.log", app_name).as_str(), Box::new(policy))
        .expect("Failed to create rolling file appender");

    // Build log4rs config
    let config = Config::builder()
        .appender(Appender::builder().build("stdout", Box::new(stdout)))
        .appender(Appender::builder().build("rolling_file", Box::new(rolling_file)))
        .logger(Logger::builder().build("tao", log::LevelFilter::Error)) // 设置tao logger为error级别
        .build(
            Root::builder()
                .appender("stdout")
                .appender("rolling_file")
                .build(log::LevelFilter::Info),
        )
        .expect("Failed to build log4rs config");

    // Initialize logger with this config
    log4rs::init_config(config).expect("Failed to initialize logger");
    //log4rs::init_file("log.yaml", Default::default()).unwrap();

    log::info!("{} start", app_name);
}
